#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
火之夜工作室 工具函数

包含各种实用工具函数
"""

import os
import re


def print_colored(text, color):
    """
    打印彩色文本
    """
    colors = {
        'red': '\033[91m',
        'green': '\033[92m',
        'yellow': '\033[93m',
        'blue': '\033[94m',
        'purple': '\033[95m',
        'cyan': '\033[96m',
        'end': '\033[0m'
    }
    print(f"{colors.get(color, '')}{text}{colors['end']}")




def get_input(prompt, default=None):
    """
    获取用户输入，支持默认值
    """
    if default:
        result = input(f"{prompt} [{default}]: ")
        return result if result else default
    else:
        return input(f"{prompt}: ")

def validate_project_name(name):
    """
    验证项目名称是否符合Flutter项目命名规范
    """
    if not re.match(r'^[a-z][a-z0-9_]*$', name):
        print_colored("错误: 项目名称必须以小写字母开头，只能包含小写字母、数字和下划线", "red")
        return False
    return True

def validate_package_name(name):
    """
    验证包名是否符合Java包名规范
    """
    if not re.match(r'^[a-z][a-z0-9_]*(.[a-z][a-z0-9_]*)*$', name):
        print_colored("错误: 包名必须符合Java包名规范，如com.example.myapp", "red")
        return False
    return True


def update_readme(target_dir, project_name, display_name):
    """
    更新README.md文件
    """
    from datetime import datetime
    current_date = datetime.now().strftime('%Y-%m-%d')
    
    readme_path = os.path.join(target_dir, 'README.md')
    with open(readme_path, 'w', encoding='utf-8') as f:
        f.write(f"# {display_name}\n\n")
        f.write(f"基于火之夜工作室 Flutter 通用项目框架创建\n\n")
        f.write(f"## 项目信息\n\n")
        f.write(f"- 项目名称: {project_name}\n")
        f.write(f"- 创建日期: {current_date}\n\n")
        f.write(f"## 快速开始\n\n")
        f.write(f"```bash\n")
        f.write(f"# 安装依赖\n")
        f.write(f"flutter pub get\n\n")
        f.write(f"# 运行项目\n")
        f.write(f"flutter run\n")
        f.write(f"```\n")


def open_project_in_ide(target_dir, ide_type="vscode"):
    """
    在IDE中自动打开项目
    
    Args:
        target_dir: 项目目录路径
        ide_type: IDE类型，可选值为 "vscode", "android_studio", "manual", "open_folder"
    """
    try:
        import subprocess
        import platform
        import os
        import shlex
        
        # 确保路径是绝对路径
        target_dir = os.path.abspath(target_dir)
        
        # 如果用户选择手动打开，直接提示
        if ide_type == "manual":
            print_colored("请手动打开项目", "yellow")
            print_colored(f"项目路径: {target_dir}", "yellow")
            return True
            
        # 如果用户选择直接打开项目文件夹
        if ide_type == "open_folder":
            system = platform.system()
            try:
                if system == 'Darwin':  # macOS
                    subprocess.run(['open', target_dir])
                    print_colored("已打开项目文件夹", "green")
                elif system == 'Windows':
                    # Windows上处理路径中的空格
                    subprocess.run(['explorer', target_dir], shell=True)
                    print_colored("已打开项目文件夹", "green")
                elif system == 'Linux':
                    # 尝试多种Linux文件管理器
                    file_managers = ['xdg-open', 'nautilus', 'thunar', 'dolphin', 'nemo', 'caja', 'pcmanfm']
                    opened = False
                    for fm in file_managers:
                        try:
                            # 在Linux上使用which命令检查文件管理器是否存在
                            which_cmd = ['which', fm]
                            result = subprocess.run(which_cmd, capture_output=True, text=True)
                            if result.returncode == 0:
                                subprocess.run([fm, target_dir])
                                print_colored(f"已使用{fm}打开项目文件夹", "green")
                                opened = True
                                break
                        except Exception:
                            continue
                    
                    if not opened:
                        print_colored("未找到合适的文件管理器，请手动打开项目文件夹", "yellow")
                        print_colored(f"项目路径: {target_dir}", "yellow")
                        return False
                else:
                    print_colored(f"不支持的操作系统: {system}，请手动打开项目文件夹", "yellow")
                    print_colored(f"项目路径: {target_dir}", "yellow")
                    return False
                return True
            except Exception as e:
                print_colored(f"打开项目文件夹失败: {str(e)}", "red")
                print_colored(f"请手动打开项目，路径: {target_dir}", "yellow")
                return False
        
        # 尝试打开VS Code
        if ide_type == "vscode":
            system = platform.system()
            vscode_found = False
            vscode_paths = []
            
            if system == 'Windows':
                # Windows上检查VS Code的常见安装路径
                win_vscode_paths = [
                    os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Microsoft VS Code', 'bin', 'code.cmd'),
                    os.path.join(os.environ.get('ProgramFiles', ''), 'Microsoft VS Code', 'bin', 'code.cmd'),
                    os.path.join(os.environ.get('ProgramFiles(x86)', ''), 'Microsoft VS Code', 'bin', 'code.cmd'),
                    'code.cmd',  # 如果在PATH中
                    'code'       # 有些Windows安装可能使用这个命令
                ]
                
                for path in win_vscode_paths:
                    try:
                        # 在Windows上使用where命令检查VS Code是否存在
                        if path in ['code.cmd', 'code']:
                            where_cmd = ['where', path]
                            result = subprocess.run(where_cmd, capture_output=True, text=True, shell=True)
                            if result.returncode == 0:
                                vscode_found = True
                                vscode_paths.append(path)
                        elif os.path.exists(path):
                            vscode_found = True
                            vscode_paths.append(path)
                    except Exception:
                        continue
            elif system == 'Darwin' or system == 'Linux':
                # macOS和Linux上使用which命令检查
                try:
                    which_cmd = ['which', 'code']
                    result = subprocess.run(which_cmd, capture_output=True, text=True)
                    if result.returncode == 0:
                        vscode_found = True
                        vscode_paths.append('code')
                except Exception:
                    pass
                
                # 检查macOS上的常见安装路径
                if system == 'Darwin':
                    mac_vscode_paths = [
                        '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code',
                        '/usr/local/bin/code',
                        os.path.expanduser('~/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code')
                    ]
                    
                    for path in mac_vscode_paths:
                        if os.path.exists(path):
                            vscode_found = True
                            vscode_paths.append(path)
            
            if vscode_found:
                # 尝试所有可能的路径
                for vscode_path in vscode_paths:
                    try:
                        if system == 'Windows':
                            # Windows上处理路径中的空格
                            subprocess.run([vscode_path, target_dir], shell=True)
                        else:
                            subprocess.run([vscode_path, target_dir])
                        print_colored("已在VS Code中打开项目", "green")
                        return True
                    except Exception as e:
                        print_colored(f"使用路径 {vscode_path} 打开VS Code失败: {str(e)}", "yellow")
                        continue
            else:
                print_colored("未找到VS Code，请手动打开项目", "yellow")
                print_colored(f"项目路径: {target_dir}", "yellow")
                return False
        
        # 尝试打开Android Studio
        elif ide_type == "android_studio":
            system = platform.system()
            studio_found = False
            studio_paths = []
            
            if system == 'Windows':
                # Windows上检查Android Studio的常见安装路径
                win_studio_paths = [
                    os.path.join(os.environ.get('ProgramFiles', ''), 'Android', 'Android Studio', 'bin', 'studio64.exe'),
                    os.path.join(os.environ.get('ProgramFiles(x86)', ''), 'Android', 'Android Studio', 'bin', 'studio64.exe'),
                    'studio64.exe',  # 如果在PATH中
                    'studio.exe'     # 有些Windows安装可能使用这个命令
                ]
                
                for path in win_studio_paths:
                    try:
                        if path in ['studio64.exe', 'studio.exe']:
                            where_cmd = ['where', path]
                            result = subprocess.run(where_cmd, capture_output=True, text=True, shell=True)
                            if result.returncode == 0:
                                studio_found = True
                                studio_paths.append(path)
                        elif os.path.exists(path):
                            studio_found = True
                            studio_paths.append(path)
                    except Exception:
                        continue
            elif system == 'Darwin' or system == 'Linux':
                # macOS和Linux上使用which命令检查
                try:
                    which_cmd = ['which', 'studio']
                    result = subprocess.run(which_cmd, capture_output=True, text=True)
                    if result.returncode == 0:
                        studio_found = True
                        studio_paths.append('studio')
                except Exception:
                    pass
                
                # 检查macOS上的常见安装路径
                if system == 'Darwin':
                    mac_studio_paths = [
                        '/Applications/Android Studio.app/Contents/MacOS/studio',
                        os.path.expanduser('~/Applications/Android Studio.app/Contents/MacOS/studio')
                    ]
                    
                    for path in mac_studio_paths:
                        if os.path.exists(path):
                            studio_found = True
                            studio_paths.append(path)
            
            if studio_found:
                # 尝试所有可能的路径
                for studio_path in studio_paths:
                    try:
                        if system == 'Windows':
                            # Windows上处理路径中的空格
                            subprocess.run([studio_path, target_dir], shell=True)
                        else:
                            subprocess.run([studio_path, target_dir])
                        print_colored("已在Android Studio中打开项目", "green")
                        return True
                    except Exception as e:
                        print_colored(f"使用路径 {studio_path} 打开Android Studio失败: {str(e)}", "yellow")
                        continue
            else:
                print_colored("未找到Android Studio，请手动打开项目", "yellow")
                print_colored(f"项目路径: {target_dir}", "yellow")
                return False
        
        # 如果都失败了，提示用户手动打开
        print_colored("未能自动打开IDE，请手动打开项目", "yellow")
        print_colored(f"项目路径: {target_dir}", "yellow")
        
    except Exception as e:
        print_colored(f"自动打开项目失败: {str(e)}", "red")
        print_colored(f"请手动打开项目，路径: {target_dir}", "yellow")
        return False
    
    return True

   